import React from 'react';
import { Routes, Route, Navigate, Link, useLocation } from 'react-router-dom';
import { Layout, Menu } from 'antd';
import './styles/modern-ui.css';
import {
  DashboardOutlined,
  UserOutlined,
  AppstoreOutlined,
  ShoppingCartOutlined,
  GiftOutlined,
  BarChartOutlined,
  SettingOutlined,
  TrophyOutlined,
  UserAddOutlined,
  DollarOutlined,
  TeamOutlined,
  FileTextOutlined,
  PieChartOutlined,
  LineChartOutlined,
  AreaChartOutlined,
  FundOutlined,
  AccountBookOutlined,
  MoneyCollectOutlined
} from '@ant-design/icons';
import Dashboard from './components/Dashboard';
import SimpleDashboard from './components/SimpleDashboard';
import TestDashboard from './components/TestDashboard';
import MinimalDashboard from './components/MinimalDashboard';
import Users from './components/Users';
import MenuPage from './components/MenuPage';
import ModernOrders from './components/ModernOrders';
import Coupons from './components/Coupons';
import Reports from './components/Reports';
import System from './components/System';
import SocialMediaReview from './components/SocialMediaReview';
import InviteManagement from './components/InviteManagement';
import Login from './components/Login';
import DebugLogin from './components/DebugLogin';
import MinimalTest from './components/MinimalTest';
import TestSimple from './components/TestSimple';
import BasicTest from './components/BasicTest';
import SimpleTest from './components/SimpleTest';
import NoRouterApp from './components/NoRouterApp';
import ErrorBoundary from './components/ErrorBoundary';
import LayoutWrapper from './components/LayoutWrapper';

const { Header, Sider, Content } = Layout;

const PrivateRoute = ({ children }) => {
  const token = localStorage.getItem('admin_token');
  
  if (!token) {
    return (
      <div style={{ 
        padding: '50px', 
        textAlign: 'center', 
        backgroundColor: '#fff3cd', 
        border: '1px solid #ffeaa7', 
        borderRadius: '8px',
        margin: '20px'
      }}>
        <h2 style={{ color: '#856404' }}>🔐 认证问题检测到</h2>
        <p style={{ color: '#856404', fontSize: '16px' }}>Dashboard页面需要登录token才能访问。</p>
        <p style={{ color: '#856404' }}>这就是为什么页面会闪现然后变白的原因。</p>
        <div style={{ marginTop: '20px' }}>
          <button 
            onClick={() => {
              localStorage.setItem('admin_token', 'debug-token-' + Date.now());
              window.location.reload();
            }}
            style={{
              backgroundColor: '#28a745',
              color: 'white',
              border: 'none',
              padding: '12px 24px',
              borderRadius: '6px',
              cursor: 'pointer',
              marginRight: '10px',
              fontSize: '14px'
            }}
          >
            🔧 设置调试Token并重新加载
          </button>
          <button 
            onClick={() => window.location.href = '/login'}
            style={{
              backgroundColor: '#007bff',
              color: 'white',
              border: 'none',
              padding: '12px 24px',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '14px'
            }}
          >
            🚪 前往登录页面
          </button>
        </div>
        <div style={{ marginTop: '20px', fontSize: '14px', color: '#6c757d' }}>
          <p>调试信息:</p>
          <p>• 当前时间: {new Date().toLocaleString()}</p>
          <p>• 页面路径: {window.location.pathname}</p>
          <p>• Token状态: 未找到</p>
        </div>
      </div>
    );
  }
  
  return children;
};

const AppContent = () => {
  return (
    <Layout style={{ 
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)'
    }}>
      <Sider 
        width={200} 
        style={{ 
          background: 'rgba(255, 255, 255, 0.95)',
          backdropFilter: 'blur(20px)',
          borderRight: '1px solid rgba(0, 0, 0, 0.06)',
          boxShadow: '4px 0 24px rgba(0, 0, 0, 0.08)'
        }}
      >
        <div style={{ 
          padding: '20px 16px', 
          borderBottom: '1px solid rgba(0, 0, 0, 0.06)',
          background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
          margin: '8px',
          borderRadius: '12px',
          boxShadow: '0 4px 12px rgba(102, 126, 234, 0.3)'
        }}>
          <h3 style={{ 
            color: '#fff', 
            margin: 0, 
            textAlign: 'center',
            fontWeight: '600',
            textShadow: '0 2px 4px rgba(0, 0, 0, 0.2)'
          }}>管理后台</h3>
        </div>
        <Menu
          mode="inline"
          defaultSelectedKeys={['dashboard']}
          style={{ 
            height: '100%', 
            borderRight: 0,
            background: 'transparent',
            padding: '8px'
          }}
          className="modern-menu"
          items={[
            { key: 'dashboard', icon: <DashboardOutlined />, label: <Link to="/dashboard">仪表盘</Link> },
            { key: 'users', icon: <UserOutlined />, label: <Link to="/users">用户管理</Link> },
            { key: 'menu', icon: <AppstoreOutlined />, label: <Link to="/menu">菜单管理</Link> },
            { key: 'orders', icon: <ShoppingCartOutlined />, label: <Link to="/orders">订单管理</Link> },
            { key: 'coupons', icon: <GiftOutlined />, label: <Link to="/coupons">优惠券管理</Link> },
            { key: 'social-review', icon: <TrophyOutlined />, label: <Link to="/social-review">社交媒体审核</Link> },
            { key: 'invite-management', icon: <UserAddOutlined />, label: <Link to="/invite-management">邀请码管理</Link> },
            { 
              key: 'reports', 
              icon: <BarChartOutlined />, 
              label: '报表管理',
              children: [
                {
                  key: 'sales-category',
                  icon: <DollarOutlined />,
                  label: '销售报表',
                  children: [
                    { key: 'daily-sales', label: <Link to="/reports?category=sales&type=daily">日销售报表</Link> },
                    { key: 'monthly-sales', label: <Link to="/reports?category=sales&type=monthly">月销售报表</Link> },
                    { key: 'product-sales', label: <Link to="/reports?category=sales&type=product">产品销售报表</Link> },
                    { key: 'cash-report', label: <Link to="/reports?category=sales&type=cash">现金申报</Link> }
                  ]
                },
                {
                  key: 'user-category',
                  icon: <TeamOutlined />,
                  label: '用户报表',
                  children: [
                    { key: 'user-growth', label: <Link to="/reports?category=user&type=growth">用户增长报表</Link> },
                    { key: 'user-activity', label: <Link to="/reports?category=user&type=activity">用户活跃度报表</Link> },
                    { key: 'user-retention', label: <Link to="/reports?category=user&type=retention">用户留存报表</Link> }
                  ]
                },
                {
                  key: 'order-category',
                  icon: <FileTextOutlined />,
                  label: '订单报表',
                  children: [
                    { key: 'order-summary', label: <Link to="/reports?category=order&type=summary">订单汇总报表</Link> },
                    { key: 'order-trend', label: <Link to="/reports?category=order&type=trend">订单趋势报表</Link> },
                    { key: 'order-status', label: <Link to="/reports?category=order&type=status">订单状态报表</Link> }
                  ]
                },
                {
                  key: 'financial-category',
                  icon: <AccountBookOutlined />,
                  label: '财务报表',
                  children: [
                    { key: 'revenue-report', label: <Link to="/reports?category=financial&type=revenue">收入报表</Link> },
                    { key: 'cost-report', label: <Link to="/reports?category=financial&type=cost">成本报表</Link> },
                    { key: 'profit-report', label: <Link to="/reports?category=financial&type=profit">利润报表</Link> },
                    { key: 'tax-report', label: <Link to="/reports?category=financial&type=tax">税务报表</Link> }
                  ]
                }
              ]
            },
            { key: 'system', icon: <SettingOutlined />, label: <Link to="/system">系统管理</Link> }
          ]}
        />
      </Sider>
      <Layout>
        <Header style={{ 
          background: 'rgba(255, 255, 255, 0.95)', 
          padding: '0 32px', 
          borderBottom: '1px solid rgba(0, 0, 0, 0.06)',
          backdropFilter: 'blur(20px)',
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
          display: 'flex',
          alignItems: 'center'
        }}>
          <h2 style={{ 
            margin: 0,
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text',
            fontWeight: '700',
            fontSize: '24px'
          }}>标准管理后台</h2>
        </Header>
        <Content style={{ 
          margin: '16px', 
          padding: 0, 
          background: 'transparent', 
          minHeight: 280,
          borderRadius: '16px',
          overflow: 'hidden'
        }} className="fade-in">
          <Routes>
            <Route path="/" element={<Navigate to="/dashboard" replace />} />
            <Route path="/dashboard" element={
              <PrivateRoute>
                 <Dashboard />
               </PrivateRoute>
            } />
            <Route path="/test-dashboard" element={<MinimalDashboard />} />
            <Route path="/users" element={<Users />} />
            <Route path="/menu" element={<MenuPage />} />
            <Route path="/orders" element={<ModernOrders />} />
            <Route path="/coupons" element={<Coupons />} />
            <Route path="/social-review" element={<SocialMediaReview />} />
            <Route path="/invite-management" element={<InviteManagement />} />
            <Route path="/reports" element={<Reports />} />
            <Route path="/system" element={<System />} />
          </Routes>
        </Content>
      </Layout>
    </Layout>
  )
}

export default function App() {
  return (
    <ErrorBoundary>
      <Routes>
        <Route path="/no-router" element={<NoRouterApp />} />
        <Route path="/simple-test" element={<SimpleTest />} />
        <Route path="/basic-test" element={<BasicTest />} />
        <Route path="/minimal-test" element={<MinimalTest />} />
        <Route path="/simple-dashboard" element={<SimpleDashboard />} />
        <Route path="/login" element={<Login />} />
        <Route path="/" element={<Navigate to="/dashboard" replace />} />
        <Route path="/dashboard" element={
          <PrivateRoute>
            <LayoutWrapper>
              <Dashboard />
            </LayoutWrapper>
          </PrivateRoute>
        } />
        <Route path="/users" element={
          <PrivateRoute>
            <LayoutWrapper>
              <Users />
            </LayoutWrapper>
          </PrivateRoute>
        } />
        <Route path="/menu" element={
          <PrivateRoute>
            <LayoutWrapper>
              <MenuPage />
            </LayoutWrapper>
          </PrivateRoute>
        } />
        <Route path="/orders" element={
          <PrivateRoute>
            <LayoutWrapper>
              <ModernOrders />
            </LayoutWrapper>
          </PrivateRoute>
        } />
        <Route path="/coupons" element={
          <PrivateRoute>
            <LayoutWrapper>
              <Coupons />
            </LayoutWrapper>
          </PrivateRoute>
        } />
        <Route path="/social-review" element={
          <PrivateRoute>
            <LayoutWrapper>
              <SocialMediaReview />
            </LayoutWrapper>
          </PrivateRoute>
        } />
        <Route path="/invite-management" element={
          <PrivateRoute>
            <LayoutWrapper>
              <InviteManagement />
            </LayoutWrapper>
          </PrivateRoute>
        } />
        <Route path="/reports" element={
          <PrivateRoute>
            <LayoutWrapper>
              <Reports />
            </LayoutWrapper>
          </PrivateRoute>
        } />
        <Route path="/system" element={
          <PrivateRoute>
            <LayoutWrapper>
              <System />
            </LayoutWrapper>
          </PrivateRoute>
        } />
      </Routes>
    </ErrorBoundary>
  );
}
